use tauri::command;
use crate::ctp_commands::ctp::types::{ApiResponse, CtpAccountConfig, MarketDataRequest};
use crate::ctp_commands::ctp::state::*;
use crate::ctp_commands::ctp::utils::{validate_login_credentials, copy_str_to_ctp_array};
use crate::logger;

// 等待登录结果（等待真实CTP回调）
fn wait_for_login_result(session_id: &str, timeout_seconds: u64) -> Result<String, String> {
    let start_time = std::time::Instant::now();
    let timeout_duration = std::time::Duration::from_secs(timeout_seconds);

    loop {
        // 检查是否超时
        if start_time.elapsed() > timeout_duration {
            return Err(format!("行情登录超时（{}秒），未收到CTP服务器响应。请检查：\n1. 网络连接是否正常\n2. 行情服务器地址是否正确\n3. 账户信息是否正确", timeout_seconds));
        }

        // 检查登录结果（来自Stream回调）
        {
            let login_results = get_login_results().lock().unwrap();
            if let Some((success, message)) = login_results.get(session_id) {
                if *success {
                    return Ok(message.clone());
                } else {
                    return Err(message.clone());
                }
            }
        }

        // 等待100ms后重试
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
}

// 行情 API 命令
#[command]
pub fn md_login(
    session_id: String,
    config: CtpAccountConfig,
) -> ApiResponse<String> {
    // 验证登录凭据
    if let Err(validation_error) = validate_login_credentials(&config) {
        return ApiResponse {
            success: false,
            data: None,
            error: Some(validation_error),
        };
    }

    // 保存会话登录信息
    {
        let mut session_info = get_session_login_info().lock().unwrap();
        session_info.insert(session_id.clone(), config.clone());
    }

    // 清除之前的登录结果
    {
        let mut login_results = get_login_results().lock().unwrap();
        login_results.remove(&session_id);
    }

    match std::panic::catch_unwind(|| {
        let mut apis = get_md_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 注册前置服务器
            let md_front = std::ffi::CString::new(config.md_front.clone()).unwrap();
            api.register_front(md_front);

            // 初始化API
            api.init();

            // 等待连接建立
            std::thread::sleep(std::time::Duration::from_millis(2000));

            // 构造登录请求
            let mut login_req = ctp_trade_lib::CThostFtdcReqUserLoginField::default();

            // 设置经纪公司代码
            copy_str_to_ctp_array(&config.broker_id, &mut login_req.BrokerID);

            // 设置用户代码
            copy_str_to_ctp_array(&config.account, &mut login_req.UserID);

            // 设置密码
            copy_str_to_ctp_array(&config.password, &mut login_req.Password);

            // 发送登录请求 - 添加额外的安全检查
            let login_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                api.req_user_login(&mut login_req, 1)
            }));

            match login_result {
                Ok(result) if result == 0 => {
                    // 等待登录结果
                    match wait_for_login_result(&session_id, 10) {
                        Ok(success_msg) => {
                            // 设置登录状态
                            let mut md_status = get_md_login_status().lock().unwrap();
                            md_status.insert(session_id.clone(), true);
                            
                            // 记录行情登录成功日志
                            logger::log_user_login(&config.account, &config.broker_id, true, None);
                            Ok(success_msg)
                        },
                        Err(error_msg) => {
                            // 记录行情登录失败日志
                            logger::log_user_login(&config.account, &config.broker_id, false, Some(&error_msg));
                            Err(error_msg)
                        }
                    }
                },
                Ok(result) => {
                    let error_msg = format!("MD login request failed with code: {}", result);
                    logger::log_user_login(&config.account, &config.broker_id, false, Some(&error_msg));
                    Err(error_msg)
                },
                Err(_) => {
                    let error_msg = "MD login request panicked - possible memory corruption".to_string();
                    logger::log_user_login(&config.account, &config.broker_id, false, Some(&error_msg));
                    Err(error_msg)
                }
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "MD login panicked".to_string();
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn subscribe_market_data(
    session_id: String,
    request: MarketDataRequest,
) -> ApiResponse<String> {
    match std::panic::catch_unwind(|| {
        let mut apis = get_md_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            // 转换合约代码为CString
            let instruments: Vec<std::ffi::CString> = request.instrument_ids
                .iter()
                .map(|id| std::ffi::CString::new(id.as_str()).unwrap())
                .collect();

            let count = instruments.len() as std::os::raw::c_int;

            // 订阅行情
            let result = api.subscribe_market_data(instruments, count);

            if result == 0 {
                // 记录市场数据订阅成功日志
                logger::log_market_data_query(&request.instrument_ids, true, None);
                Ok(format!("Successfully subscribed to {} instruments", request.instrument_ids.len()))
            } else {
                let error_msg = format!("Failed to subscribe market data, error code: {}", result);
                // 记录市场数据订阅失败日志
                logger::log_market_data_query(&request.instrument_ids, false, Some(&error_msg));
                Err(error_msg)
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(message)) => {
            ApiResponse {
                success: true,
                data: Some(message),
                error: None,
            }
        },
        Ok(Err(error)) => {
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Subscribe market data panicked".to_string();
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

#[command]
pub fn unsubscribe_market_data(
    _session_id: String,
    request: MarketDataRequest,
) -> ApiResponse<String> {
    // 实现取消订阅行情数据的逻辑
    ApiResponse {
        success: true,
        data: Some(format!("Unsubscribed from {} instruments", request.instrument_ids.len())),
        error: None,
    }
}

